/**
 * 定时任务启动工厂
 */
package cn.com.klun.factory;


import cn.com.klun.build.TaskBuildSource;
import cn.com.klun.cache.QuartzConstants;
import cn.com.klun.cache.QuartzPropertiesCache;
import cn.com.klun.cache.QuartzTaskConfigCache;
import cn.com.klun.netty.ServerIpAndPortSet;
import cn.com.klun.netty.client.NettyClientStartup;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Timer;

/**
 * @author chenmin-ds
 * 定时任务启动工厂
 */
public class TimerTaskClientStartFactory {

	private Logger logger = LoggerFactory.getLogger("TimerTaskStartFactory");
	
	private TaskInfoLoadInitsFactory taskInfoLoadInitsFactory;
	
	private TaskBuildSource taskBuildSourceProxy;
	
	private TaskListenerClientFactory taskListenerClientFactory;
	
	public void inits(){
		logger.info("任务系统启动，开始初始化任务链......");
		
		QuartzPropertiesCache.loadingClient();
		Thread a = new Thread(){

			@Override
			public void run() {
				//计算服务端的IP和端口是否可用
				if(QuartzConstants.TASK_INFO_LOAD_TYPE_REMOTE.equals(QuartzPropertiesCache.getTaskInfoLoadType())){
					ServerIpAndPortSet.setIpPort();
					taskListenerClientFactory.setTaskBuildSourceProxy(taskBuildSourceProxy);
					NettyClientStartup.getInstance().setBusinessObject(taskListenerClientFactory);
					NettyClientStartup.getInstance().setTaskBuildSource(taskBuildSourceProxy);
					NettyClientStartup.getInstance().start();
					
					//任务链初始化
					taskInfoLoadInitsFactory.loadTaskInfoRemote();
				}else{
					//任务链初始化
					initsTaskRun();
				}
				
				//任务链变更修正
				updateTask();
			}
		};
		a.start();
		
	}
	
	private void initsTaskRun(){
		try{
			logger.info("任务链初始化开始......");
			List<JSONObject> list = taskInfoLoadInitsFactory.loadTaskInfoDao();
			for(JSONObject object : list){
				taskBuildSourceProxy.initsTask(object);
				QuartzTaskConfigCache.setTaskInfo(object.getString("taskNo"), object);
			}
			logger.info("任务系统启动成功，初始化任务链成功......");
		}catch(Exception e){
			logger.error("任务链初始化异常:",e);
		}
	}
	
	private void updateTask(){
		try{
			// TODO 看一下报错的问题
			logger.info("任务链变更修正开始......");
			Timer timer = new Timer();
			timer.schedule(new ChildTimerUpdateFactory(taskBuildSourceProxy,taskInfoLoadInitsFactory),
					QuartzPropertiesCache.getTaskUpdateTimeLong() * 1000
					,QuartzPropertiesCache.getTaskUpdateTimeLong() * 1000);
		}catch(Exception e){
			logger.error("任务链变更修正异常:",e);
		}
	}

	public void setTaskInfoLoadInitsFactory(
			TaskInfoLoadInitsFactory taskInfoLoadInitsFactory) {
		this.taskInfoLoadInitsFactory = taskInfoLoadInitsFactory;
	}

	public void setTaskBuildSourceProxy(TaskBuildSource taskBuildSourceProxy) {
		this.taskBuildSourceProxy = taskBuildSourceProxy;
	}

	public void setTaskListenerClientFactory(
			TaskListenerClientFactory taskListenerClientFactory) {
		this.taskListenerClientFactory = taskListenerClientFactory;
	}
	
}
